import { getCurrentInstance, useSSRContext, onServerPrefetch } from "vue";

export function usePiniaRef() {
	let pinia = getCurrentInstance()!.appContext.config.globalProperties.$pinia;
	return pinia.state;
}

export function useSaveSSRPinia() {
	if (!import.meta.env.SSR) {
		return () => {};
	}
	let pinia = usePiniaRef();
	let context = useSSRContext()!;
	return () => {
		context.store = pinia.value;
	};
}

export function saveSSRPinia(initPinia: Function) {
	let savePinia = useSaveSSRPinia();
	onServerPrefetch(async () => {
		if (import.meta.env.SSR) {
			await initPinia();
			savePinia();
		}
	});
}
